package com.example.administrator.hqq.activity.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.View.alertview.AlertView;
import com.example.administrator.hqq.View.alertview.AlertViewFactory;
import com.example.administrator.hqq.View.alertview.OnItemClickListener;
import com.example.administrator.hqq.activity.register.HeadPortraitActivity;;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.bean.QNTokenBean;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.utils.CameraUtils;
import com.example.administrator.hqq.utils.HintWordsUtils;
import com.example.administrator.hqq.utils.MyTextUtils;
import com.example.administrator.hqq.utils.SketchTextWatcher;
import com.example.administrator.hqq.utils.UploadManagerUtils;
import com.example.administrator.hqq.utils.transform.GlideCircleTransform;
import com.google.gson.Gson;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class AmendUserDataActivity extends MyActivity {

    @BindView(R.id.return_auto)
    AutoRelativeLayout returnAuto;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.report_auto)
    AutoRelativeLayout reportAuto;
    @BindView(R.id.user_name)
    EditText userName;
    @BindView(R.id.default_head_portrait)
    ImageView defaultHeadPortrait;
    @BindView(R.id.uploading_head_portrait)
    ImageView uploadingHeadPortrait;
    @BindView(R.id.setting)
    Button continueSetting;
    private String url="";
    private QNTokenBean qnTokenBean;
    private String TAG=this.getClass().getSimpleName();
    private AlertView photoTypeAlertView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amend_user_data);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initview();
    }

    private void initview() {
        userName.setText(getIntent().getStringExtra(LoongsConfig.user_name));
        SketchTextWatcher sketchTextWatcher = new SketchTextWatcher(userName, 30);
        userName.addTextChangedListener(sketchTextWatcher);
    }

    @OnClick({R.id.return_auto, R.id.default_head_portrait, R.id.uploading_head_portrait, R.id.setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.return_auto:
                finish();
                break;
            case R.id.default_head_portrait:
                //跳转到默认头像选择页面
                Intent intent = new Intent(this, HeadPortraitActivity.class);
                startActivityForResult(intent,20);
                break;
            case R.id.uploading_head_portrait:
                //选择拍摄或者相册
                photoTypeAlertView = AlertViewFactory.getInstance().getPhotoTypeAlertView(this, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == -1) {
                            photoTypeAlertView.dismiss();
                        } else if (position == 0) {
                            AmendUserDataActivityPermissionsDispatcher.startLocationWithCheck(AmendUserDataActivity.this);
                        } else if (position == 1) {
                            AmendUserDataActivityPermissionsDispatcher.startStorageWithCheck(AmendUserDataActivity.this);
                        }
                    }
                });
                photoTypeAlertView.show();
                break;
            case R.id.setting:
                if(!TextUtils.isEmpty(url))
                {
                    showLoadingDialog();
                    setUrl();

                }
                if (!TextUtils.isEmpty(userName.getText()))
                {
                    if (MyTextUtils.isEmptyString(userName))
                    {
                        ToastUtils.showShort("昵称不能全是空格");
                        return;
                    }
                    if (!userName.getText().toString().equals(getIntent().getStringExtra(LoongsConfig.user_name)))
                    {
                        OkHttpUtils.get().url(UrlFactory.setNickName())
                                .addParams(LoongsConfig.user_id, SPUtils.getInstance().getString(LoongsConfig.user_id))
                                .addParams(LoongsConfig.nickname,userName.getText().toString())
                                .build().execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                dismissLoadingDialog();
                                Log.e(TAG, "设置用户昵称onError: " );
                                ToastUtils.showShort("修改失败请稍后重试");
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                dismissLoadingDialog();
                                Log.e(TAG, "设置用户昵称onResponse: "+response );
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    HintWordsUtils.showMarkeWords(jsonObject.getInt(LoongsConfig.code),jsonObject.getString(LoongsConfig.description));
                                    if (jsonObject.getInt(LoongsConfig.code)==200)
                                    {
                                        ToastUtils.showShort("修改成功");
                                        EventBus.getDefault().post(LoongsConfig.updateMine);
                                        finish();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    } else{
                        finish();
                    }
                }
                break;
        }
    }
    /**
     * 申请权限
     */
    @SuppressLint("NoCorrespondingNeedsPermission")
    @OnShowRationale({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForLocation(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("申请相机权限")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForLocation() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForLocation() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startLocation() {
        CameraUtils.getInstance().takeCamera(this);
    }

    @OnShowRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showRetionaleForStorage(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage(getString(R.string.storage_permission))
                .setPositiveButton(getString(R.string.agree), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(getString(R.string.refuse), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    @OnNeverAskAgain(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showNeverAskForStorage() {
        Toast.makeText(this, getString(R.string.permission_never_ask), Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void showDeniedForStorage() {
        Toast.makeText(this, getString(R.string.permission_denied), Toast.LENGTH_SHORT).show();
    }

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    public void startStorage() {
        CameraUtils.getInstance().openAlbum(this);
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AmendUserDataActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==20&&resultCode==111)
        {
            if (!TextUtils.isEmpty(data.getStringExtra(LoongsConfig.picName)))
            {
                url=data.getStringExtra(LoongsConfig.picName);
                String pic_url = data.getStringExtra(LoongsConfig.pic_Url);
                defaultHeadPortrait.setImageResource(getResourceID(pic_url));
                uploadingHeadPortrait.setImageDrawable(getDrawable(R.drawable.uploading_head_portrait));
                Log.e(TAG, "onActivityResult: "+url );
            }
        }
        CameraUtils.getInstance().onActivityResult(this, requestCode, resultCode, data, new CameraUtils.OnResultListener() {
            @Override
            public void takePhotoFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()){
                    CameraUtils.getInstance().cropPicture(AmendUserDataActivity.this, path,1,1);//裁剪图片
                }
            }

            @Override
            public void selectPictureFinish(String path) {
                File picFile = new File(path);
                if (picFile.exists()){
                    CameraUtils.getInstance().cropPicture(AmendUserDataActivity.this, path,1,1);//裁剪图片
                }
            }
            @Override
            public void cropPictureFinish(String path) {
                getQNToken(path);
            }
        });
    }
    public void getQNToken(String path) {
        final File picFile = new File(path);
        showLoadingDialog();
        OkHttpUtils.get().url(UrlFactory.getQNToken())
                .addParams(LoongsConfig.id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.type, LoongsConfig.USER)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String s,int id) {
                Log.e(TAG, "onResponse: " + s);
                Gson gson = new Gson();
                qnTokenBean = gson.fromJson(s, QNTokenBean.class);
                if (qnTokenBean.getCode() == 200)
                    UploadManagerUtils.getUploadManager().put(picFile, qnTokenBean.getKey(), qnTokenBean.getToken(), new UpCompletionHandler() {
                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                        @Override
                        public void complete(String key, ResponseInfo info, JSONObject res) {
                            //res包含hash、key等信息，具体字段取决于上传策略的设置
                            if (info.isOK()) {
                                url=qnTokenBean.getId();
                                defaultHeadPortrait.setImageDrawable(getDrawable(R.drawable.default_head_portrait));
                                Glide.with(AmendUserDataActivity.this)
                                        .load(qnTokenBean.getUrl())
                                        .bitmapTransform(new GlideCircleTransform(AmendUserDataActivity.this))
                                        .into(uploadingHeadPortrait);
                            } else {
                                //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                            }
                            dismissLoadingDialog();
                            Log.i("qiniu", key + ", " + info + ", " + res);
                        }
                    }, null);
            }
        });
    }

    private void setUrl() {
        OkHttpUtils.get().url(UrlFactory.setUrl())
                .addParams(LoongsConfig.user_id,SPUtils.getInstance().getString(LoongsConfig.user_id))
                .addParams(LoongsConfig.url,url)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: "+e.getMessage() );
                dismissLoadingDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: "+response );
                dismissLoadingDialog();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt(LoongsConfig.code)==200)
                    {
                        ToastUtils.showShort("头像修改成功");
                        EventBus.getDefault().post(LoongsConfig.updateMine);

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(String i) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissLoadingDialog();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    public int  getResourceID(String imageName){
        Context ctx=getBaseContext();
        int resId = getResources().getIdentifier(imageName, "drawable", ctx.getPackageName());
        //如果没有在"mipmap"下找到imageName,将会返回0
        return resId;
    }
}
